<template>
  <!-- 高级查询 -->
  <div class="app-container">
    <el-form v-show="searchVisible" ref="queryForm" :model="queryParams" :inline="true">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="queryParams.roleName" size="small" style="width: 240px" placeholder="请输入角色名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="角色编码" prop="roleCode">
        <el-input v-model="queryParams.roleCode" size="small" style="width: 240px" placeholder="请输入角色编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" size="small" style="width: 240px" placeholder="角色状态" clearable>
          <el-option v-for="option in options.sysRoleStatusOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="createTimeRange" value-format="yyyy-MM-dd" type="daterange" size="small" style="width: 240px" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermission="['system:role:insert']" type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['system:role:update']" type="success" icon="el-icon-edit" size="mini" :disabled="isSingle" @click="handleEdit">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermission="['system:role:delete']" type="danger" icon="el-icon-delete" size="mini" :disabled="isMultiple" @click="handleRemove">删除</el-button>
      </el-col>
      <right-toolbar :show-search.sync="searchVisible" @queryTable="handleQuery" />
    </el-row>

    <!-- 数据列表 -->
    <el-table v-loading="loading" :data="page.records" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="角色名称" prop="roleName" sortable show-overflow-tooltip width="150" />
      <el-table-column label="角色编码" prop="roleCode" sortable show-overflow-tooltip width="150" />
      <el-table-column label="排序" prop="sort" width="100" />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermission="['system:role:update']" size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
          <el-button v-hasPermission="['system:role:update']" size="mini" type="text" icon="el-icon-circle-check" @click="handleRoleDataScope(scope.row)">数据权限</el-button>
          <el-button v-hasPermission="['system:role:delete']" size="mini" type="text" icon="el-icon-delete" @click="handleRemove(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="page.total>0" :total="page.total" :page.sync="page.current" :limit.sync="page.pageSize" @pagination="handleQuery" />

    <!-- 添加/修改对话框 -->
    <el-dialog :title="sysRoleFormDialog.title" :visible.sync="sysRoleFormDialog.visible" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form ref="sysRoleForm" :model="sysRoleFormData" :rules="sysRoleFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="sysRoleFormData.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="sysRoleFormData.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="角色顺序" prop="sort">
          <el-input-number v-model="sysRoleFormData.sort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="sysRoleFormData.status">
            <el-radio v-for="option in options.sysRoleStatusOptions" :key="option.dictValueCode" :label="option.dictValueCode">{{ option.dictValueName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-checkbox v-model="menuExpand" @change="handleMenuCheckedTreeExpand($event)">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleMenuCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
          <el-tree
            ref="menu"
            :data="options.menuOptions"
            :props="{children: 'children', label: 'label'}"
            class="tree-border"
            show-checkbox
            node-key="id"
            empty-text="加载中，请稍后"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="sysRoleFormData.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSysRoleFormDialog">确 定</el-button>
        <el-button @click="resetSysRoleFormDialog">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="roleDataScopeDialog.title" :visible.sync="roleDataScopeDialog.visible" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form :model="sysRoleFormData" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="sysRoleFormData.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="sysRoleFormData.roleCode" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="sysRoleFormData.dataScopeType">
            <el-option v-for="option in options.dataScopeTypeOptions" :key="option.dictValueCode" :label="option.dictValueName" :value="option.dictValueCode" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="sysRoleFormData.dataScopeType === 'CUSTOM'" label="数据权限">
          <el-checkbox v-model="deptExpand" @change="handleOrgCheckedTreeExpand($event)">展开/折叠</el-checkbox>
          <el-checkbox v-model="deptNodeAll" @change="handleOrgCheckedTreeNodeAll($event, 'org')">全选/全不选</el-checkbox>
          <el-tree
            ref="org"
            :data="options.sysOrgOptions"
            :props="{children: 'children', label: 'label'}"
            class="tree-border"
            node-key="id"
            empty-text="加载中，请稍后"
            show-checkbox
            default-expand-all
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmRoleDataScopeDialog">确 定</el-button>
        <el-button @click="resetRoleDataScopeDialog">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import RoleApi from '@/api/system/RoleApi'
import MenuApi from '@/api/system/MenuApi'
import OrgApi from '@/api/system/OrgApi'
import DictValueApi from '@/api/system/DictValueApi'

const defaultSysRoleFormData = {
  id: undefined,
  roleName: undefined,
  roleCode: undefined,
  dataScopeType: 'SELF',
  sort: 10,
  status: '0',
  menuIds: [],
  orgIds: [],
  remark: undefined
}
export default {
  name: 'Role',
  data() {
    return {
      options: {
        sysRoleStatusOptions: [],
        dataScopeTypeOptions: [],
        sysOrgOptions: [],
        menuOptions: []
      },
      queryParams: {
        roleName: undefined,
        roleCode: undefined,
        status: undefined,
        sortProperty: null,
        sortDirection: null
      },
      page: {
        current: 1,
        pageSize: 10,
        total: 0,
        records: []
      },
      sysRoleFormDialog: {
        title: '',
        visible: false
      },
      sysRoleFormData: Object.assign({}, defaultSysRoleFormData),
      sysRoleFormRules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        roleCode: [{ required: true, message: '角色编码不能为空', trigger: 'blur' }],
        sort: [{ required: true, message: '角色顺序不能为空', trigger: 'blur' }]
      },
      roleDataScopeDialog: {
        title: '分配数据权限',
        visible: false
      },
      loading: true,
      isSingle: true,
      isMultiple: true,
      searchVisible: true,
      multipleSelection: [],
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      createTimeRange: []
    }
  },
  created() {
    this.handleQuery()
    this.loadOptions()
  },
  methods: {
    loadOptions() {
      DictValueApi.list({ dictCode: 'sys_enable_disable' }).then(response => {
        this.options.sysRoleStatusOptions = response.data
      })
      DictValueApi.list({ dictCode: 'sys_data_scope_type' }).then(response => {
        this.options.dataScopeTypeOptions = response.data
      })
      OrgApi.treeSelect().then(response => {
        this.options.sysOrgOptions = response.data
      })
      MenuApi.treeSelect().then(response => {
        this.options.menuOptions = response.data
      })
    },
    handleAdd() {
      this.openSysRoleFormDialog()
    },
    handleRemove(row) {
      const ids = row.id || this.multipleSelection.map(item => item.id)
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return RoleApi.remove(ids)
      }).then(() => {
        this.handleQuery()
        this.$message.success('删除成功')
      })
    },
    handleEdit(row) {
      const id = row.id || this.multipleSelection.map(item => item.id)[0]
      this.openSysRoleFormDialog(id)
    },
    handleQuery() {
      this.loading = true
      RoleApi.page(this.$common.addDateRange(this.queryParams, this.createTimeRange), this.page).then(response => {
        this.page.records = response.data.records
        this.page.total = response.data.total
        this.loading = false
      }, () => {
        this.loading = false
      })
    },
    handleExport() {
      const queryParams = this.queryParams
      this.$confirm('是否确认导出数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return RoleApi.export(queryParams)
      }).then(response => {
        this.$common.download(response.data)
      })
    },
    handleSortChange(sort) {
      if (sort.order) {
        this.queryParams.sortProperty = sort.prop
        this.queryParams.sortDirection = sort.order === 'ascending' ? 'asc' : 'desc'
      } else {
        this.queryParams.sortProperty = null
        this.queryParams.sortDirection = null
      }
      this.handleQuery()
    },
    handleStatusChange(row) {
      const display = row.status === '0' ? '启用' : '停用'
      this.$confirm('确认要"' + display + '"角色吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return RoleApi.edit({ id: row.id, status: row.status })
      }).then(() => {
        this.$message.success(display + '成功')
        this.handleQuery()
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    handleRoleDataScope(row) {
      const id = row.id || this.multipleSelection.map(item => item.id)[0]
      this.openRoleDataScopeDialog(id)
    },
    openSysRoleFormDialog(id) {
      this.resetSysRoleFormDialog()
      this.sysRoleFormDialog.visible = true
      if (id) {
        this.sysRoleFormDialog.title = '角色-修改'
        RoleApi.get(id).then(response => {
          this.sysRoleFormData = response.data
          const roleMenus = this.sysRoleFormData.roleMenus
          if (roleMenus || this.roleMenus.length > 0) {
            this.$refs.menu.setCheckedKeys(roleMenus.map(menu => menu.id))
          }
        })
      } else {
        this.sysRoleFormDialog.title = '角色-添加'
      }
    },
    confirmSysRoleFormDialog() {
      this.$refs['sysRoleForm'].validate(valid => {
        if (valid) {
          this.sysRoleFormData.menuIds = this.getMenuAllCheckedKeys()
          if (this.sysRoleFormData.id) {
            RoleApi.updateRoleMenus(this.sysRoleFormData).then(response => {
              this.$message.success('修改成功')
              this.sysRoleFormDialog.visible = false
              this.handleQuery()
            })
          } else {
            RoleApi.add(this.sysRoleFormData).then(response => {
              this.$message.success('新增成功')
              this.sysRoleFormDialog.visible = false
              this.handleQuery()
            })
          }
        }
      })
    },
    resetSysRoleFormDialog() {
      this.sysRoleFormDialog = {
        title: '',
        visible: false
      }
      if (this.$refs.menu !== undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      this.menuExpand = false
      this.menuNodeAll = false
      this.deptExpand = true
      this.deptNodeAll = false
      this.sysRoleFormData = Object.assign({}, defaultSysRoleFormData)
      this.resetForm('sysRoleForm')
    },
    openRoleDataScopeDialog(id) {
      this.resetSysRoleFormDialog()
      this.roleDataScopeDialog.visible = true
      RoleApi.get(id).then(response => {
        this.sysRoleFormData = response.data
        const roleOrgs = this.sysRoleFormData.roleOrgs
        if (roleOrgs || roleOrgs.length > 0) {
          this.$refs.org.setCheckedKeys(roleOrgs.map(menu => menu.id))
        }
      })
    },
    confirmRoleDataScopeDialog() {
      if (this.sysRoleFormData.id) {
        if (this.sysRoleFormData.dataScopeType === 'CUSTOM') {
          this.sysRoleFormData.orgIds = this.getOrgAllCheckedKeys()
        } else {
          this.sysRoleFormData.orgIds = []
        }
        RoleApi.updateDataScope(this.sysRoleFormData).then(response => {
          this.$message.success('修改成功')
          this.roleDataScopeDialog.visible = false
          this.handleQuery()
        })
      }
    },
    resetRoleDataScopeDialog() {
      this.roleDataScopeDialog.visible = false
      this.resetSysRoleFormDialog()
    },
    // 所有选中的节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 树权限（展开/折叠）
    handleMenuCheckedTreeExpand(value) {
      const treeList = this.options.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
      }
    },
    // 树权限（全选/全不选）
    handleMenuCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.options.menuOptions : [])
    },
    // 所有选中的节点数据
    getOrgAllCheckedKeys() {
      // 目前被选中的组织节点
      const checkedKeys = this.$refs.org.getCheckedKeys()
      // 半选中的组织节点
      const halfCheckedKeys = this.$refs.org.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    // 树权限（展开/折叠）
    handleOrgCheckedTreeExpand(value) {
      const treeList = this.options.sysOrgOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.org.store.nodesMap[treeList[i].id].expanded = value
      }
    },
    // 树权限（全选/全不选）
    handleOrgCheckedTreeNodeAll(value) {
      this.$refs.org.setCheckedNodes(value ? this.options.sysOrgOptions : [])
    },
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.isSingle = selection.length !== 1
      this.isMultiple = !selection.length
    },
    resetQuery() {
      this.page.current = 1
      this.createTimeRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
